package team.pwy.service;

import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import team.pwy.consts.RbmConsts;
import team.pwy.mapper.*;
import team.pwy.pojo.entity.Message;
import team.pwy.pojo.entity.Order;
import com.rabbitmq.client.Channel;
import team.pwy.pojo.entity.Seat;
import team.pwy.util.CreatJedis;

import java.io.IOException;
import java.util.*;

@Component
public class OrderServiceImpl {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private SessionMapper sessionMapper;

    @Resource
    private CouponMapper couponMapper;

    @Resource
    private SeatMapper seatMapper;

    @Resource
    private WebSocketProcess webSocketProcess;

    @Resource
    private MovieMapper movieMapper;

    @Resource
    private MessageMapper messageMapper;

    @RabbitHandler
    @RabbitListener(queues = RbmConsts.ORDER_SUCCESS)
    public void successOrder(int id) {
        Order order = orderMapper.findById(id);
        try {
            Thread.sleep(500);

            String message = "您购买的电影票{" + order.getMovieTitle() + "{已支付成功,请关注场次座位信息和开场时间,祝您观影愉快!";
            Message message1 = new Message();
            message1.setUserId(order.getUserId());
            message1.setStatus(1);
            message1.setMessage(message);
            message1.setCreateTime(new Date());
            message1.setType(3);
            messageMapper.addMessage(message1);

            webSocketProcess.sendMessagezf(order.getUserId(), message);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param id:
     * @param channel:
     * @param tag:
     * @author DaiLing
     * @description 监听支付
     * @date 2024/1/24 14:50
     */
    @RabbitHandler
    @RabbitListener(queues = RbmConsts.DELAYED_ORDER_ERROR)
    public void addOrder(int id, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {

        Order order = orderMapper.findById(id);
        // 订单到时未支付
        if (order.getStatus() == 0) {
            // 查询锁定的座位
            List<Seat> seats = seatMapper.findByIds(id);
            Map<String, Object> map = new HashMap<>();
            List<Integer> list = new ArrayList<>();
            for (Seat seat : seats) {
                list.add(seat.getId());
            }
            map.put("payStatus", 0);
            map.put("orderId", null);
            map.put("ids", list);
            // 将锁定的座位状态改为未选择
            seatMapper.updateByIds(map);
            // 将订单状态改为支付超时
            orderMapper.updateById(id, 1);
            // 退还优惠卷
            if (Objects.nonNull(order.getCouponId())) {
                couponMapper.updateByCouponId(0, order.getCouponId());
            }
            // 更新影厅购票人数
            sessionMapper.updateById(order.getSessionId(), order.getQuota());

            String message = "您购买的电影票{" + order.getMovieTitle() + "{已支付成功,请关注场次座位信息和开场时间,祝您观影愉快!";
            Message message1 = new Message();
            message1.setUserId(order.getUserId());
            message1.setStatus(1);
            message1.setMessage(message);
            message1.setCreateTime(new Date());
            message1.setType(4);
            messageMapper.addMessage(message1);

            try {
                // 将消息发送给用户
                webSocketProcess.sendMessagezf(order.getUserId(), message);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // 移除用户选择的座位
            List<Integer> allSelectSeatId = orderMapper.findByOrderId(order.getId());
            Jedis jedis = CreatJedis.getJedis();
            for (Integer selectSeatId : allSelectSeatId)
                jedis.srem("seat", String.valueOf(selectSeatId));
        }

        // 确认消费
        try {
            channel.basicAck(tag, false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RabbitHandler
    @RabbitListener(queues = RbmConsts.ORDERSUCCESS_QUEUE)
    public void orderSuccessQueue(Map<String, Integer> map, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        int orderId = map.get("id");
        orderMapper.updateById(orderId, map.get("payStatus"));
        Order order = orderMapper.findById(orderId);
        movieMapper.updateGrossed(order.getQuota() * order.getMoviePrice(), order.getMovieId());
    }
}
